import { defineStore } from 'pinia'
import router, { constantRoutes, dynamicRoutes } from '@/router'
// import { useRouter } from 'vue-router';
const modules = import.meta.glob("../views/**/*.vue")
const Layout = ()=>import('@/layout/index.vue')
export const useRoutesStore = defineStore('routes', {
    state: () => {
        return {
            routes: [] as Array<RouteRecordRaw>,
        }
    },
    getters: {

    },
    actions: {
        // 添加动态路由，并同步到状态管理器中
        addRoutes(data: Array<any>, router: any) {
            // data.forEach(f => {
            //     this.routes.push({
            //         path: f.path,
            //         name: f.name,
            //         meta:f.meta,
            //         // 错误示例：components:()=>import(`../views/Pages/${m.component}`)
            //         // 正确示例如下：
            //         component: modules[`../views/${f.component}`],
            //     })
            // })
            // this.routes.forEach(f => router.addRoute(f))
            if(data?.length){
                localStorage.setItem('menus',JSON.stringify(data))
            }
            this.routes = filterAsyncRouter(data)
            this.routes.forEach(route => { router.addRoute(route) })
            console.log(router.getRoutes())
        }
    }
})
const filterAsyncRouter = (asyncRouterMap:any,lastRouter = false,type=false) => {
    return asyncRouterMap.filter(route => {
        // if (type && route.children) {
        //     route.children = filterChildren(route.children)
        // }
        if (route.component) {
            // Layout ParentView 组件特殊处理
            if (route.component === 'Layout') {
                route.component = Layout
                // route.component = loadView(route.component)
            // } else if (route.component === 'ParentView') {
            //     route.component = ParentView
            // } else if (route.component === 'InnerLink') {
            //     route.component = InnerLink
            } else {
                route.component = loadView(route.component)
            }
        }
        if (route.children != null && route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children, route, type)
        } else {
            delete route['children']
            delete route['redirect']
        }
        return true
    })

}
export const loadView = (view:any) => {
    let res;
    for (const path in modules) {
        const dir = path.split('views/')[1].split('.vue')[0];
        if (dir === view) {
            res = modules[path];
        }
    }
    return res;
}